package com.bsu.ascm.operation;

import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.afree.chart.AFreeChart;
import org.afree.chart.ChartFactory;
import org.afree.chart.axis.DateAxis;
import org.afree.chart.plot.XYPlot;
import org.afree.chart.renderer.xy.XYItemRenderer;
import org.afree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.afree.data.time.Day;
import org.afree.data.time.TimeSeries;
import org.afree.data.time.TimeSeriesCollection;
import org.afree.data.xy.XYDataset;
import org.afree.graphics.SolidColor;
import org.afree.ui.RectangleInsets;
import org.apache.http.client.ClientProtocolException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.bsu.ascm.ChartBaseView;
import com.bsu.ascm.R;
import com.bsu.ascm.http.AscmHttpClient;
import com.bsu.ascm.tool.AscmEnvironment;
import com.bsu.ascm.tool.Utils;

public class QualityObjectLineChart extends Activity {
	private ChartBaseView cbv = null;														//图标基类
	private String[] s_qualityobject = new String[3];										//质量目标数据
	private String[] s_workspace = new String[3];											//工作空间
	private AscmHttpClient http = new AscmHttpClient();										//请求http数据
	private TimeSeriesCollection tsc = new TimeSeriesCollection();							//时间序列
	private XmlPullParserFactory xpp_factory = null;										//XmlPullParser工厂
	private XmlPullParser xpp = null;														//获得XmlPullParser对象
	
	private TimeSeries ts_complete = null;													//实际完成数量
	private TimeSeries ts_object = null;													//目标完成数量
	private Day day = null;
	private float value_complete = .0f;														//实际完成数量值
	private float value_object = .0f;														//目标完成数量值
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);						//设置横屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);											//无title  
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,    					//全屏
                       WindowManager.LayoutParams. FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qualityobject);
		init();
	}
	/**
	 * 初始化界面函数
	 */
	private void init(){
		Calendar c = Calendar.getInstance();
		
		//初始化年
		Spinner sp_year = (Spinner)findViewById(R.id.sp_year);
		final String[] s_year = {"2009","2010","2011","2012","2013","2014","2015"};
		ArrayAdapter<String> adp_year = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,s_year);
		adp_year.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_year.setAdapter(adp_year);
		int year = c.get(Calendar.YEAR);
		sp_year.setSelection(Utils.getDataPosition(s_year, Integer.toString(year)),true);					//设置sp_year的默认值
		
		//初始化月
		Spinner sp_month = (Spinner)findViewById(R.id.sp_month);
		String[] s_month = {"1","2","3","4","5","6","7","8","9","10","11","12"};
		ArrayAdapter<String> adp_month = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,s_month);
		adp_month.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_month.setAdapter(adp_month);
		int month = c.get(Calendar.MONTH);
		sp_month.setSelection(Utils.getDataPosition(s_month, Integer.toString(month)), true);				//设置sp_month的默认值

		//车型
		Spinner sp_cartype = (Spinner)findViewById(R.id.sp_cartype);
		String[] s_cartype = {"B70","B70-A","B70-B","J56","J61","J61-4SD","J61-5HB","B50","J44","全部"};
		ArrayAdapter<String> adp_cartype = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,s_cartype);
		adp_cartype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_cartype.setAdapter(adp_cartype);
		//质量目标
		Spinner sp_qualityobject = (Spinner)findViewById(R.id.sp_qualityobject);
		s_qualityobject[0] = "质量一次校验合格率";
		s_qualityobject[1] = "漏雨合格比率";
		s_qualityobject[2] = "DPU";
		ArrayAdapter<String> adp_qualityobject = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,s_qualityobject);
		adp_qualityobject.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_qualityobject.setAdapter(adp_qualityobject);
		//车间
		Spinner sp_workspace = (Spinner)findViewById(R.id.sp_workspace);
		s_workspace[0] = "一工厂总装";
		s_workspace[1] = "一工厂涂装";
		s_workspace[2] = "一工厂焊装";
		ArrayAdapter<String> adp_workspace = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,s_workspace);
		adp_workspace.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_workspace.setAdapter(adp_workspace);
		
		//初始化按钮
		Button bt_query = (Button)findViewById(R.id.bt_query);
		bt_query.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View arg0) {
				dataRequest();
			}
		});

		//初始化图表
		cbv = new ChartBaseView(this);
		
		final AFreeChart chart = createChart(tsc);
		cbv.setChart(chart);
		LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		cbv.setLayoutParams(lp);
		
		//将图表加入layout中
		LinearLayout ll_chart = (LinearLayout) findViewById(R.id.ll_chart);							//获得装载chart的Layout
		ll_chart.addView(cbv,AscmEnvironment.getInstance().getDisplayWidth(),									//增加chart进去
				AscmEnvironment.getInstance().getDisplayHeight()
				-sp_year.getHeight()-sp_cartype.getHeight());
		
		Log.d("height", Integer.toString(sp_year.getMeasuredHeight()));
		
		//初始化xml解析
		try {
			xpp_factory = XmlPullParserFactory.newInstance();
			xpp = xpp_factory.newPullParser();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建一个线型图表
	 * @param dataset	带入数据
	 * @return			返回图表对象
	 */
	private AFreeChart createChart(XYDataset dataset){
		//创建Chart对象
		AFreeChart chart = ChartFactory.createTimeSeriesChart(
				"质量目标完成", 					//标题
				"日期", 							//X轴标签
				"数量", 							//Y轴标签
				dataset, 						//数据
				true, 							//是否创建图例
				true, 							//是否生成提示
				false);							//是否生成URL？？？
		
		chart.setBackgroundPaintType(new SolidColor(Color.WHITE));		//设置背景色
		XYPlot plot = (XYPlot) chart.getPlot();							//获得XYPlot
		plot.setBackgroundPaintType(new SolidColor(Color.LTGRAY));		//设置plot白灰色
		plot.setDomainGridlinePaintType(new SolidColor(Color.WHITE));	//设置区域格线白色
		plot.setRangeGridlinePaintType(new SolidColor(Color.WHITE));	//设置行列线白色
		plot.setAxisOffset(new RectangleInsets(5.0,5.0,5.0,5.0));		//设置坐标偏移
		plot.setDomainCrosshairVisible(true);			
		plot.setRangeCrosshairVisible(true);
		
		XYItemRenderer r = plot.getRenderer();
		if(r instanceof XYLineAndShapeRenderer){
			XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
			renderer.setBaseShapesVisible(true);
			renderer.setBaseShapesFilled(true);
			renderer.setDrawSeriesLineAsPath(true);
		}
		
		DateAxis axis = (DateAxis) plot.getDomainAxis();
		axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
		
		return chart;
	}
	/**
	 * 请求图表数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws XmlPullParserException 
	 */
	private void dataRequest() {
		String xml = "";
		try {
			xml = http.query("QMFullCarQuality", getParam());
			parseXML(xml);
			int eventType = xpp.getEventType();
			while(eventType != XmlPullParser.END_DOCUMENT){
				String nodeName = xpp.getName();
				switch(eventType){
				case XmlPullParser.START_DOCUMENT:
					ts_complete = new TimeSeries("实际完成");
					ts_object = new TimeSeries("目标完成");
					break;
				case XmlPullParser.START_TAG:
					if("NDATE".equals(nodeName))
						day = splitNDATE(xpp.nextText());
					else if("QTY".equals(nodeName))
						value_complete = Float.parseFloat(xpp.nextText());
					else if("TQTY".equals(nodeName))
						value_object = Float.parseFloat(xpp.nextText());
					break;
				case XmlPullParser.END_TAG:
					if("Table".equals(nodeName)){
						ts_complete.add(day,value_complete);
						ts_object.add(day,value_object);
					}
					break;
				default:
					break;
				}
				eventType = xpp.next();
			}
		
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tsc.removeAllSeries();
		tsc.addSeries(ts_complete);
		tsc.addSeries(ts_object);
		final AFreeChart chart = createChart(tsc);
		cbv.setChart(chart);
	}
	/**
	 * 解析xml
	 * @param xml 代入的xml数据 
	 * @throws XmlPullParserException 
	 */
	private void parseXML(String xml) throws XmlPullParserException{
		StringReader sr = new StringReader(xml);
		xpp.setInput(sr);
		
	}
	
	private String getParam(){
		String param = "";
		//获得wpitemno参数
		Spinner sp_wpitemno = (Spinner)findViewById(R.id.sp_cartype);
		String wpitemno = sp_wpitemno.getSelectedItem().toString();
		if(wpitemno.equals("全部"))
			wpitemno = "%";
		
		//获得ctype参数
		Spinner sp_ctype = (Spinner)findViewById(R.id.sp_qualityobject);
		String ctype = sp_ctype.getSelectedItem().toString();
		if(ctype.equals(s_qualityobject[0]))
			ctype = "ZTL";
		else if(ctype.equals(s_qualityobject[1]))
			ctype = "LYL";
		else if(ctype.equals(s_qualityobject[2]))
			ctype = "DPU";

		//获得term参数activity
		Spinner sp_year = (Spinner)findViewById(R.id.sp_year);
		Spinner sp_month = (Spinner)findViewById(R.id.sp_month);
		String t_month = sp_month.getSelectedItem().toString();
		if(Integer.parseInt(t_month)<10)																//如果月份小于10，在月份前加0
			t_month = "0"+t_month;
		String term = sp_year.getSelectedItem().toString()+t_month;
		
		//获得orgid参数
		Spinner sp_workspace = (Spinner)findViewById(R.id.sp_workspace);
		String orgid = sp_workspace.getSelectedItem().toString();
		if(orgid.equals(s_workspace[0]))
			orgid = "1";
		else if(orgid.equals(s_workspace[1]))
			orgid = "39";
		else if(orgid.equals(s_workspace[2]))
			orgid = "40";
		
		return "wpitemno="+wpitemno+"&ctype="+ctype+"&term="+term+"&orgid="+orgid;
		//return "wpitemno=B70&ctype=ZTL&term=201106&orgid=1";
	}
	

	/**
	 * 解析NDATE数据
	 * @param ndate
	 * @return 返回Day对象
	 */
	private Day splitNDATE(String ndate){
		return new Day(Integer.parseInt(ndate.substring(6, 8)),Integer.parseInt(ndate.substring(4, 6)),Integer.parseInt(ndate.substring(0,4))); 
	}
}
